package org.ajie.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import org.ajie.config.annotation.RestControllerMapping;
import org.ajie.entity.SysUser;
import org.ajie.model.Result;
import org.ajie.service.SysUserService;
import org.ajie.utils.PasswordUtils;
import org.ajie.vo.Login;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

import static org.ajie.model.Result.error;

@RestControllerMapping("login")
public class LoginController {

    @Resource
    private SysUserService  sysUserService;

    @SaIgnore
    @PostMapping("username")
    @Operation(summary = "用户登录")
    public Result<Map<String,String>> login(@RequestBody Login login){
        SysUser user = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, login.getUsername()));
        if (user == null){
            return Result.error("用户不存在");
        }
        // 校验密码是否正确
        String password = login.getPassword();
        String slat = user.getSlat();
        String decrypt = PasswordUtils.decrypt(slat, user.getPassword());
        if (password.equals(decrypt)){
            StpUtil.login(user.getId());
            Map<String, String> map = new HashMap<>();
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            map.put("tokeninfo",tokenInfo.tokenName);
            map.put("token", tokenInfo.getTokenValue());
            return Result.success(map);
        }
        return error("用户名或密码错误");
    }

    @GetMapping("logout")
    @Operation(summary = "用户登出")
    public Result<Boolean> logout(){
        StpUtil.logout();
        return Result.success();
    }


    @GetMapping("test")
    @SaCheckPermission("login:test")
    public Result<String> test(){
        return Result.success("test");
    }
}
